<?php

namespace addons\shopro\job;

use addons\shopro\model\Cats;
use addons\shopro\model\GoodsComment;
use addons\shopro\model\Order;
use addons\shopro\model\OrderAction;
use addons\shopro\model\OrderItem;
use addons\shopro\model\Config;
use app\admin\model\AdminLog;
use app\admin\model\CatOrder;
use app\api\controller\Demo;
use app\common\library\Sms as Smslib;
use app\common\model\UserBaofuBank;
use baofu\Baofu;
use baofu\Util\Log;
use think\Controller;
use think\queue\Job;
use think\Loader;
use think\Db;
use addons\shopro\model\User;

/**
 * 订单自动操作
 */
class OrderAutoOper extends BaseJob
{

    /**
     * 订单自动关闭
     */
    public function autoClose(Job $job, $data)
    {
        try {
            $order = $data['order'];

            // 重新查询订单
            $order = Order::get($order['id']);

            if ($order && $order['status'] == 0) {
                \think\Db::transaction(function () use ($order, $data) {
                    // 订单关闭前
                    \think\Hook::listen('order_close_before', $data);
                    // 执行关闭
                    $order->status = Order::STATUS_INVALID;
                    $order->ext = json_encode($order->setExt($order, ['invalid_time' => time()]));      // 取消时间
                    $order->save();

                    OrderAction::operAdd($order, null, null, 'system', '系统自动失效订单');

                    // 订单自动关闭之后 行为 返还用户优惠券，积分
                    $data = ['order' => $order];
                    \think\Hook::listen('order_close_after', $data);
                });
            }

            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            \think\Log::write('queue-' . get_class() . '-autoClose' . '：执行失败，错误信息：' . $e->getMessage());
        }
    }

    /**
     * 猫咪订单自动关闭
     */
    public function catsAutoClose(Job $job, $data)
    {
        $insert = [
            'title' => '猫咪订单自动关闭',
            'content' => !is_scalar($data) ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data,
            'url' => substr(request()->url(), 0, 1500),
            'admin_id' => 1,
            'username' => '猫咪订单自动关闭',
            'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
            'ip' => request()->ip()
        ];
        AdminLog::insert($insert);
        try {
            $order = $data['order'];
            // 重新查询订单
            $order = CatOrder::get($order['order_id']);
            if ($order && $order['status'] == 0) {
                CatOrder::where('order_sn', $order['order_sn'])->update(['status' => '-2', 'updatetime' => time()]);
                Cats::where('id', $order['cat_id'])->update(['type' => 1]);
            }
            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            \think\Log::write('queue-' . get_class() . '-catsAutoClose' . '：执行失败，错误信息：' . $e->getMessage());
        }
    }

    // 签约扣款失败后 再次发起扣款
    public function orderPayedAfter(Job $job, $data)
    {
        $insert = [
            'title' => '签约扣款失败后 再次发起扣款',
            'content' => !is_scalar($data) ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data,
            'url' => substr(request()->url(), 0, 1500),
            'admin_id' => 1,
            'username' => '签约扣款失败后 再次发起扣款',
            'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
            'ip' => request()->ip()
        ];
        AdminLog::insert($insert);
        $unsign = new BaofuPay();
        $order_sn = $data['order_sn'];
        $unsign->pay($order_sn, 2);
    }

    /**
     * 订单自动确认
     */
    public function autoConfirm(Job $job, $data)
    {
        try {
            $order = $data['order'];
            $item = $data['item'];

            // 重新查询订单
            $order = Order::get($order['id']);

            // 只要没有退款成功，所有队列正常执行
            $item = OrderItem::where('id', $item['id'])
                ->where('dispatch_status', OrderItem::DISPATCH_STATUS_SENDED)
                ->where('refund_status', 'not in', [OrderItem::REFUND_STATUS_OK, OrderItem::REFUND_STATUS_FINISH])
                ->find();

            if ($order && $item) {
                \think\Db::transaction(function () use ($order, $item, $data) {
                    (new Order())->getedItem($order, $item, ['oper_type' => 'system']);
                });
            }

            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            \think\Log::write('queue-' . get_class() . '-autoConfirm' . '：执行失败，错误信息：' . $e->getMessage());
        }
    }

    //测试
    public function test(Job $job, $data)
    {
        try {
            echo time();
            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            \think\Log::write('queue-' . get_class() . '-autoConfirm' . '：执行失败，错误信息：' . $e->getMessage());
        }
    }


    public function autoComment(Job $job, $data)
    {
        try {
            $order = $data['order'];
            $item = $data['item'];

            // 重新查询订单
            $order = Order::get($order['id']);

            // 只要没有退款成功，所有队列正常执行
            $item = OrderItem::where('id', $item['id'])
                ->where('dispatch_status', OrderItem::DISPATCH_STATUS_GETED)
                ->where('comment_status', OrderItem::COMMENT_STATUS_NO)
                ->where('refund_status', 'not in', [OrderItem::REFUND_STATUS_OK, OrderItem::REFUND_STATUS_FINISH])
                ->find();

            if ($order && $item) {
                \think\Db::transaction(function () use ($order, $item, $data) {
                    // 订单评价前
                    \think\Hook::listen('order_comment_before', $data);

                    // 获取自动好评内容
                    $config = Config::where('name', 'order')->cache(300)->find();        // 读取配置自动缓存 5 分钟
                    $config = isset($config) ? json_decode($config['value'], true) : [];
                    $comment_content = (isset($config['order_comment_content']) && $config['order_comment_content'])
                        ? $config['order_comment_content'] : '用户默认好评';       // 单位天

                    GoodsComment::create([
                        'goods_id' => $item['goods_id'],
                        'order_id' => $order['id'],
                        'user_id' => $order['user_id'],
                        'level' => 5,           // 自动好评
                        'content' => $comment_content,
                        'images' => '',
                        'status' => 'show'
                    ]);

                    $item->comment_status = OrderItem::COMMENT_STATUS_OK;        // 评价成功
                    $item->save();

                    OrderAction::operAdd($order, $item, null, 'system', '系统自动评价成功');

                    // 订单评价后
                    $data = ['order' => $order, 'item' => $item];
                    \think\Hook::listen('order_comment_after', $data);
                });
            }

            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            \think\Log::write('queue-' . get_class() . '-autoComment' . $e->getMessage());
        }
    }

    /**
     * 绑定结果查询
     */
    public function baofuQueryBind(Job $job, $data)
    {
        try {
            $bank = $data['baofu'];
            $item = $data['item'];

            // 重新查询订单
            $bank = UserBaofuBank::get($bank['id']);

            if ($bank['status'] == 4) {
                $config = Db::name('config')->where('group', 'baofu')->column('value', 'name');

                //处理中
                Loader::import("\baofu\baofu", EXTEND_PATH);
                $this->baofu = new \baofu\Baofu($config);
                $result = $this->baofu->queryBind($bank['card_code'], $bank['user_id']);
                if ($result['resp_code'] = "S") {
                    //绑卡成功
                    $data = [
                        'protocol_no' => $result['data']['protocol_no'],
                        'status' => 2,
                        'updatetime' => time(),
                        'confirmtime' => time()
                    ];

                    (new UserBaofuBank())->where('id', $bank['id'])->update($data);

                    $insert = [
                        'title' => '签约成功',
                        'content' => '签约成功',
                        'url' => substr(request()->url(), 0, 1500),
                        'admin_id' => 1,
                        'username' => '签约成功',
                        'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
                        'ip' => request()->ip()
                    ];
                    AdminLog::insert($insert);

                    //获得待签约订单
                    CatOrder::where('id', $bank['order_id'])
                        ->where('status', 0)//订单状态:-2=交易关闭,-1=已取消,0=待签约,1=已签约,2=已完成
                        ->update([
                            'status' => 1,
                            'agreement_no' => $result['data']['protocol_no'],
                            'protocol_no' => $result['data']['protocol_no'],
                            'cycletime' => time()
                        ]);
                    $orderInfo = CatOrder::where('id', $bank['order_id'])->find();

                    $RiskItem = array();
                    $RiskItem["goodsCategory"] = "01";//商品类目 详见附录《商品类目》
                    $RiskItem["chPayIp"] = "127.0.0.1";//持卡人支付IP


                    /**--------行业参数  (以下为电商行业风控参，请参看接口文档附录风控参数)-------------**/
                    $RiskItem["csName"] = $orderInfo['consignee'];    //收货人姓名
                    $RiskItem["csMobile"] = $orderInfo['phone'];  //收货人手机
                    $RiskItem["csProvince"] = $orderInfo['csProvince'];          //收货人省份
                    $RiskItem["csCity"] = $orderInfo['csCity'];             //收货人城市
                    $RiskItem["csAddress"] = $orderInfo['address'];            //收货人地址
                    $RiskItem["prodNameList"] = $orderInfo['breed_name'];       //商品名称
                    $RiskItem["prodTypeList"] = "20";       //商品类目
                    $RiskItem["prodQtyList"] = "1";        //商品数量
                    $RiskItem["prodAmtList"] = $orderInfo['total_amount'];        //商品总价
                    $RiskItem = json_encode($RiskItem);//加入风控参数(固定为JSON字串)

                    Cats::where('id', $orderInfo['cat_id'])->update(['type' => 0, 'RiskItem' => $RiskItem]);//猫咪改为已签约

                    //用户支付 TODO 分期付款
//                    $pay_time = strtotime($orderInfo['deduction_time']);
                    $pay_time = getNextMonthDays($orderInfo);
                    Log::LogWirte('支付时间:' . date('Y-m-d H:i:s', $pay_time));
                    \think\Queue::later(($pay_time - time()), '\addons\shopro\job\OrderAutoOper@baofuPay', ['order' => $orderInfo], 'shopro');

                } elseif ($result['resp_code'] = "S") {
                    //处理中，过10秒在重新调用
                    \think\Queue::later(10, '\addons\shopro\job\OrderAutoOper@baofuQueryBind', ['baofu' => $bank], 'shopro');
                }
            }
            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            \think\Log::write('queue-' . get_class() . '-baofuQueryBind' . '：绑定结果查询,执行失败，错误信息：' . $e->getMessage());
        }
    }


    /**
     * 退款结果查询
     */
    public function baofuQueryRefund(Job $job, $data)
    {
        try {
            $info = Db::name('baofu_pay')->where('trans_id', $data['refund_no'])->find();
            if ($info && $info['status'] == 3) {
                //需查询状态
                $resp_code = ['BF00100', 'BF00112', 'BF00113', 'BF00115', 'BF00307', 'BF00384', 'BF00203'];

                //处理中
                Loader::import("\baofu\baofu", EXTEND_PATH);
                $config = Db::name('config')->where('group', 'baofu')->column('value', 'name');
                $baofu = new \baofu\Refund($config);
                $result = $baofu->queryAction($data['refund_no']);


                if ($result['code'] == 200) {
                    //退款成功
                    (new CatOrder())->where('id', $info['order_id'])->update(['status' => 5, 'trade_no' => $data['refund_no'], 'refundtime' => time()]);
                    Db::name('baofu_pay')->where('trans_id', $data['refund_no'])->update(['status' => 1]);
                } elseif ($result['code'] == 201) {
                    \think\Queue::later(10, '\addons\shopro\job\OrderAutoOper@baofuQueryRefund', ['refund_no' => $data['refund_no']], 'shopro');
                } else {
                    Db::name('baofu_pay')->where('trans_id', $data['refund_no'])->update(['status' => 2]);
                }
            }

            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            \think\Log::write('queue-' . get_class() . '-baofuQueryBind' . '：执行失败，错误信息：' . $e->getMessage());
        }
    }


    /**
     * 订单扣款
     */
    public function baofuPay(Job $job, $data)
    {
        try {
            $data = $data['order'];

            $insert = [
                'title' => '周期扣款',
                'content' => !is_scalar($data) ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data,
                'url' => substr(request()->url(), 0, 1500),
                'admin_id' => 1,
                'username' => '周期扣款',
                'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
                'ip' => request()->ip(),
                'createtime' => time()
            ];
            AdminLog::insert($insert);
            $order_sn = $data['order_sn'];

            //获得待签约订单
            $orderInfo = CatOrder::where('order_sn', $order_sn)->find();

            //判断当前订单是否进行了延期扣款
            if ($orderInfo['yanqi_day'] != 0 && ($orderInfo['yanqi_day'] - 30) > time()) {
                //本次周期扣款进行了分期操作,不是真正的扣款日期,进行跳过
            } else {
                //获取当前客户剩余周期,并且订单没有解约
                if ($orderInfo['remaining_cycle'] > 0 && $orderInfo['unsign'] == 0) {
                    $month = strtotime(date('Y-m', time()));
                    // 本月已支付过就不再支付
                    $isPay = Db::name('baofu_pay')->where('order_id', $orderInfo['id'])
                        ->where('status', 1)
                        ->where('createtime', '>=', $month)
//                        ->where('DATE(FROM_UNIXTIME(createtime))', '=', date('Y-m-d'))
                        ->find();

                    //获取当前客户剩余周期
                    if (!$isPay && $orderInfo['remaining_cycle'] > 0) {
                        Loader::import("\baofu\pay", EXTEND_PATH);
                        $config = Db::name('config')->where('group', 'baofu')->column('value', 'name');
                        $baofuClass = new \baofu\Pay($config);

                        if ($orderInfo['remaining_cycle'] == $orderInfo['total_cycle']) {
                            //第一次扣款
                            $total_amount = bcmul($orderInfo['remaining_cycle'], $orderInfo['month_money'], 2);
                            $txn_amt = bcmul(bcadd($orderInfo['month_money'], bcsub($orderInfo['total_amount'], $total_amount, 2), 2), 100);


                            //第一次奖励积分
                            $integral = bcdiv($orderInfo['score_amount'], $orderInfo['total_cycle'], 2);
                            $total_integral = bcmul($integral, $orderInfo['total_cycle'], 2);
                            $integral = bcadd($integral, bcsub($orderInfo['score_amount'], $total_integral, 2), 2);
                        } else {
                            $txn_amt = bcmul($orderInfo['month_money'], 100);

                            $integral = bcdiv($orderInfo['score_amount'], $orderInfo['total_cycle'], 2);
                        }
                        //TODO 走实际支付 $txn_amt
                        $baofuData = [
                            'user_id' => $orderInfo['user_id'],
                            'txn_amt' => $txn_amt,
                            'trans_id' => $baofuClass->getTransID(),
                            'protocol_no' => $orderInfo['protocol_no'],
                            'risk_item' => $orderInfo['RiskItem']
                        ];

                        $result = $baofuClass->singlePay($baofuData);

                        $paylog = [
                            'user_id' => $orderInfo['user_id'],
                            'order_id' => $orderInfo['id'],
                            'trans_id' => $baofuData['trans_id'],
                            'type' => 'pay',
                            'memo' => '订单支付',
                            'txn_amt' => bcdiv($txn_amt, 100, 2),
                            'cycle' => ($orderInfo['total_cycle'] - $orderInfo['remaining_cycle'] + 1),
                            'createtime' => time(),
                            'notify' => is_array($result['notify']) ? json_encode($result['notify']) : $result['notify'],
                        ];

                        if ($result['code'] == 200) {
                            $paytime = time();
                            CatOrder::where('order_sn', $order_sn)->setDec('remaining_cycle', 1);

                            //检查当前剩余扣款周期
                            $info = CatOrder::where('order_sn', $order_sn)->value('remaining_cycle');
                            if ($info != 0) {
                                //下期期数
                                $paytime = getNextMonthDays($orderInfo);
                                write_log('订单id为' . $orderInfo['id'] . '，调用方法为baofuPay，支付结果为success，下次扣款时间：' . date('Y-m-d H:i:s', $paytime), 'baofuPay');
                                \think\Queue::later($paytime - time(), '\addons\shopro\job\OrderAutoOper@baofuPay', ['order' => $orderInfo], 'shopro');
                            } else {
                                Db::name('user_baofu_bank')->where('order_id', $orderInfo['id'])->where('status', 2)->update(['status' => 3, 'unbindtime' => time()]);
                            }

                            $status = $info <= 0 ? 2 : 4;
                            CatOrder::where('order_sn', $order_sn)->update([
                                'status' => $status,
                                'paytime' => $paytime,
                                'repayment' => date('d'),
                                'yanqi_day' => '0',
                            ]);


                            $user = User::get($orderInfo['user_id']);
                            $before = $user->money;
                            $after = $user->money + $integral;
                            $user->money = Db::raw('money + ' . $integral);
                            $user->save();
                            Db::name('shopro_user_wallet_log')->insert([
                                "user_id" => $orderInfo['user_id'],
                                "wallet" => $integral,       // 符号直接存到记录里面
                                "before" => $before,
                                "after" => $after,
                                "type" => 'cats_recharge',
                                "memo" => '猫咪签约奖励,奖励积分' . $integral,
                                "item_id" => $orderInfo['cat_id'],
                                "wallet_type" => "money",
                                "ext" => '',
                                "oper_type" => 'admin',
                                "oper_id" => 1,
                                'createtime' => time()
                            ]);
                            Db::name('user_money_log')->insert([
                                'user_id' => $orderInfo['user_id'],
                                'money' => $integral,
                                'before' => $before,
                                'after' => $after,
                                'memo' => '猫咪签约奖励,奖励积分' . $integral,
                                'createtime' => time()
                            ]);

                            $paylog['status'] = 1;
                        } elseif ($result['code'] == 201) {
                            //处理中
                            CatOrder::where('id', $orderInfo['id'])->where('status', 0)->update(['status' => 6]);

                            //绑定结果查询
                            \think\Queue::later(10, '\addons\shopro\job\OrderAutoOper@baofuQueryPay', ['baofuData' => $paylog], 'shopro');

                            $paylog['status'] = 3;
                        } else {
                            //订单逾期加一
                            CatOrder::where('order_sn', $order_sn)->setInc('overdue_num', 1);
//                            CatOrder::where('id', $orderInfo['id'])->where('status', 0)->update(['status' => 6]);

                            //发送失败短信
                            $mobile = Db::name('user_baofu_bank')->where('protocol_no', $orderInfo['protocol_no'])->value('phone');
                            Smslib::notice($mobile, '', 'sending_2');

                            $time = strtotime(date("Y-m-d", strtotime("+1 day")));
                            write_log('订单id为' . $orderInfo['id'] . '，调用方法为baofuPay，支付结果为fail，下次扣款时间：' . date('Y-m-d H:i:s', $time), 'baofuPay');
                            \think\Queue::later($time - time(), '\addons\shopro\job\OrderAutoOper@baofuPay', ['order' => $orderInfo], 'shopro');
                            $paylog['status'] = 2;
                        }

                        Db::name('baofu_pay')->insert($paylog);
                    }
                }
            }

            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            echo date('周期付款报错.' . $e->getMessage());
            \think\Log::write('queue-' . get_class() . '-baofuPay' . '：执行失败，错误信息：' . $e->getMessage());
        }
    }

    public function baofuPay_cs(Job $job, $data)
    {
        try {
            $data = $data['order'];

            $insert = [
                'title' => '周期扣款',
                'content' => !is_scalar($data) ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data,
                'url' => substr(request()->url(), 0, 1500),
                'admin_id' => 1,
                'username' => '周期扣款',
                'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
                'ip' => request()->ip(),
                'createtime' => time()
            ];
            AdminLog::insert($insert);
            $order_sn = $data['order_sn'];

            //获得待签约订单
            $orderInfo = CatOrder::where('order_sn', $order_sn)->find();

            //判断当前订单是否进行了延期扣款
            if ($orderInfo['yanqi_day'] != 0 && ($orderInfo['yanqi_day'] - 30) > time()) {
                //本次周期扣款进行了分期操作,不是真正的扣款日期,进行跳过
            } else {
                //获取当前客户剩余周期,并且订单没有解约
                if ($orderInfo['remaining_cycle'] > 0 && $orderInfo['unsign'] == 0) {
                    $month = strtotime(date('Y-m', time()));
                    // 本月已支付过就不再支付
                    $isPay = Db::name('baofu_pay')->where('order_id', $orderInfo['id'])
                        ->where('status', 1)
                        ->where('createtime', '>=', $month)
//                        ->where('DATE(FROM_UNIXTIME(createtime))', '=', date('Y-m-d'))
                        ->find();

                    //获取当前客户剩余周期
                    if (!$isPay && $orderInfo['remaining_cycle'] > 0) {
                        Loader::import("\baofu\pay", EXTEND_PATH);
                        $config = Db::name('config')->where('group', 'baofu')->column('value', 'name');
                        $baofuClass = new \baofu\Pay($config);

                        if ($orderInfo['remaining_cycle'] == $orderInfo['total_cycle']) {
                            //第一次扣款
                            $total_amount = bcmul($orderInfo['remaining_cycle'], $orderInfo['month_money'], 2);
                            $txn_amt = bcmul(bcadd($orderInfo['month_money'], bcsub($orderInfo['total_amount'], $total_amount, 2), 2), 100);


                            //第一次奖励积分
                            $integral = bcdiv($orderInfo['score_amount'], $orderInfo['total_cycle'], 2);
                            $total_integral = bcmul($integral, $orderInfo['total_cycle'], 2);
                            $integral = bcadd($integral, bcsub($orderInfo['score_amount'], $total_integral, 2), 2);
                        } else {
                            $txn_amt = bcmul($orderInfo['month_money'], 100);

                            $integral = bcdiv($orderInfo['score_amount'], $orderInfo['total_cycle'], 2);
                        }
                        //TODO 走实际支付 $txn_amt
                        $baofuData = [
                            'user_id' => $orderInfo['user_id'],
                            'txn_amt' => $txn_amt,
                            'trans_id' => $baofuClass->getTransID(),
                            'protocol_no' => $orderInfo['protocol_no'],
                            'risk_item' => $orderInfo['RiskItem']
                        ];

//                        $result = $baofuClass->singlePay($baofuData);
                        $result = [
                            'notify' => [],
                            'code' => 200
                        ];

                        $paylog = [
                            'user_id' => $orderInfo['user_id'],
                            'order_id' => $orderInfo['id'],
                            'trans_id' => $baofuData['trans_id'],
                            'type' => 'pay',
                            'memo' => '订单支付',
                            'txn_amt' => bcdiv($txn_amt, 100, 2),
                            'cycle' => ($orderInfo['total_cycle'] - $orderInfo['remaining_cycle'] + 1),
                            'createtime' => time(),
                            'notify' => is_array($result['notify']) ? json_encode($result['notify']) : $result['notify'],
                        ];

                        if ($result['code'] == 200) {
                            $paytime = time();
                            CatOrder::where('order_sn', $order_sn)->setDec('remaining_cycle', 1);

                            //检查当前剩余扣款周期
                            $info = CatOrder::where('order_sn', $order_sn)->value('remaining_cycle');
                            if ($info != 0) {
                                //下期期数
                                $paytime = getNextMonthDays($orderInfo);
                                write_log('订单id为' . $orderInfo['id'] . '，调用方法为baofuPay，支付结果为success，下次扣款时间：' . date('Y-m-d H:i:s', $paytime), 'baofuPay');
                                \think\Queue::later($paytime - time(), '\addons\shopro\job\OrderAutoOper@baofuPay', ['order' => $orderInfo], 'shopro');
                            } else {
                                Db::name('user_baofu_bank')->where('order_id', $orderInfo['id'])->where('status', 2)->update(['status' => 3, 'unbindtime' => time()]);
                            }

                            $status = $info <= 0 ? 2 : 4;
                            CatOrder::where('order_sn', $order_sn)->update([
                                'status' => $status,
                                'paytime' => $paytime,
                                'repayment' => date('d'),
                                'yanqi_day' => '0',
                            ]);


                            $user = User::get($orderInfo['user_id']);
                            $before = $user->money;
                            $after = $user->money + $integral;
                            $user->money = Db::raw('money + ' . $integral);
                            $user->save();
                            Db::name('shopro_user_wallet_log')->insert([
                                "user_id" => $orderInfo['user_id'],
                                "wallet" => $integral,       // 符号直接存到记录里面
                                "before" => $before,
                                "after" => $after,
                                "type" => 'cats_recharge',
                                "memo" => '猫咪签约奖励,奖励积分' . $integral,
                                "item_id" => $orderInfo['cat_id'],
                                "wallet_type" => "money",
                                "ext" => '',
                                "oper_type" => 'admin',
                                "oper_id" => 1,
                                'createtime' => time()
                            ]);
                            Db::name('user_money_log')->insert([
                                'user_id' => $orderInfo['user_id'],
                                'money' => $integral,
                                'before' => $before,
                                'after' => $after,
                                'memo' => '猫咪签约奖励,奖励积分' . $integral,
                                'createtime' => time()
                            ]);

                            $paylog['status'] = 1;
                        } elseif ($result['code'] == 201) {
                            //处理中
                            CatOrder::where('id', $orderInfo['id'])->where('status', 0)->update(['status' => 6]);

                            //绑定结果查询
                            \think\Queue::later(10, '\addons\shopro\job\OrderAutoOper@baofuQueryPay', ['baofuData' => $paylog], 'shopro');

                            $paylog['status'] = 3;
                        } else {
                            //订单逾期加一
                            CatOrder::where('order_sn', $order_sn)->setInc('overdue_num', 1);
//                            CatOrder::where('id', $orderInfo['id'])->where('status', 0)->update(['status' => 6]);

                            //发送失败短信
                            $mobile = Db::name('user_baofu_bank')->where('protocol_no', $orderInfo['protocol_no'])->value('phone');
                            Smslib::notice($mobile, '', 'sending_2');

                            $time = strtotime(date("Y-m-d", strtotime("+1 day")));
                            write_log('订单id为' . $orderInfo['id'] . '，调用方法为baofuPay，支付结果为fail，下次扣款时间：' . date('Y-m-d H:i:s', $time), 'baofuPay');
                            \think\Queue::later($time - time(), '\addons\shopro\job\OrderAutoOper@baofuPay', ['order' => $orderInfo], 'shopro');
                            $paylog['status'] = 2;
                        }

                        Db::name('baofu_pay')->insert($paylog);
                    }
                }
            }

            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            echo date('周期付款报错.' . $e->getMessage());
            \think\Log::write('queue-' . get_class() . '-baofuPay' . '：执行失败，错误信息：' . $e->getMessage());
        }
    }


    /**
     * 支付结果查询
     */
    public function baofuQueryPay(Job $job, $data)
    {
        try {
            $payData = $data['baofuData'];
            $orderInfo = CatOrder::get($payData['order_id']);

            Loader::import("\baofu\pay", EXTEND_PATH);
            $config = Db::name('config')->where('group', 'baofu')->column('value', 'name');
            $baofuClass = new \baofu\Pay($config);

            $result = $baofuClass->queryPay(['trans_id' => $payData['trans_id']]);

            if ($result['code'] == 200) {

                if ($orderInfo['remaining_cycle'] == $orderInfo['total_cycle']) {
                    //第一次奖励积分
                    $integral = bcdiv($orderInfo['score_amount'], $orderInfo['total_cycle'], 2);
                    $total_integral = bcmul($integral, $orderInfo['total_cycle'], 2);
                    $integral = bcadd($integral, bcsub($orderInfo['score_amount'], $total_integral, 2), 2);
                } else {
                    $integral = bcdiv($orderInfo['score_amount'], $orderInfo['total_cycle'], 2);
                }

                // 查询到支付成功
                $order_sn = $orderInfo['order_sn'];
                $paytime = time();
                CatOrder::where('order_sn', $order_sn)->setDec('remaining_cycle', 1);

                //检查当前剩余扣款周期
                $info = CatOrder::where('order_sn', $order_sn)->value('remaining_cycle');
                if ($info != 0) {
                    //下期期数
//                    $cycle = ($orderInfo['total_cycle'] - $info) + 1;
                    //获取下个月的时间
                    $paytime = getNextMonthDays($orderInfo);
                    write_log('订单id为' . $orderInfo['id'] . '，调用方法为baofuQueryPay，支付结果为success，下次扣款时间：' . date('Y-m-d H:i:s', $paytime), 'baofuPay');
                    \think\Queue::later($paytime - time(), '\addons\shopro\job\OrderAutoOper@baofuPay', ['order' => $orderInfo], 'shopro');
                } else {
                    Db::name('user_baofu_bank')->where('order_id', $orderInfo['id'])->where('status', 2)->update(['status' => 3, 'unbindtime' => time()]);
                }

                $status = $info <= 0 ? 2 : 4;
                CatOrder::where('order_sn', $order_sn)->update([
                    'status' => $status,
                    'paytime' => $paytime,
                    'repayment' => date('d'),
                    'yanqi_day' => '0',
                ]);


                $user = User::get($orderInfo['user_id']);
                $before = $user->money;
                $after = $user->money + $integral;
                $user->money = Db::raw('money + ' . $integral);
                $user->save();
                Db::name('shopro_user_wallet_log')->insert([
                    "user_id" => $orderInfo['user_id'],
                    "wallet" => $integral,       // 符号直接存到记录里面
                    "before" => $before,
                    "after" => $after,
                    "type" => 'cats_recharge',
                    "memo" => '猫咪签约奖励,奖励积分' . $integral,
                    "item_id" => $orderInfo['cat_id'],
                    "wallet_type" => "money",
                    "ext" => '',
                    "oper_type" => 'admin',
                    "oper_id" => 1,
                    'createtime' => time()
                ]);
                Db::name('user_money_log')->insert([
                    'user_id' => $orderInfo['user_id'],
                    'money' => $integral,
                    'before' => $before,
                    'after' => $after,
                    'memo' => '猫咪签约奖励,奖励积分' . $integral,
                    'createtime' => time()
                ]);

                $status = 1;
            } elseif ($result['code'] == 201) {
                //处理中，继续查询
                \think\Queue::later(20, '\addons\shopro\job\OrderAutoOper@baofuQueryPay', ['baofuData' => $payData], 'shopro');
                $status = 3;
            } else {
                // 查询无果即是支付失败
                //订单逾期加一
                CatOrder::where('order_sn', $orderInfo['order_sn'])->setInc('overdue_num', 1);

                //支付失败
                //发送失败短信
                $mobile = Db::name('user_baofu_bank')->where('protocol_no', $orderInfo['protocol_no'])->value('phone');
                Smslib::notice($mobile, '', 'sending_2');

                $time = strtotime(date("Y-m-d", strtotime("+1 day")));
                write_log('订单id为' . $orderInfo['id'] . '，调用方法为baofuQueryPay，支付结果为fail，下次扣款时间：' . date('Y-m-d H:i:s', $time), 'baofuPay');
                \think\Queue::later($time - time(), '\addons\shopro\job\OrderAutoOper@baofuPay', ['order' => $orderInfo], 'shopro');
                $status = 2;

            }

            $notify = json_encode($result['notify'], JSON_UNESCAPED_UNICODE);
            Db::name('baofu_pay')->where(['trans_id' => $payData['trans_id']])->update(['status' => $status, 'notify2' => $notify]);

            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            \think\Log::write('queue-' . get_class() . '-baofuQueryPay' . '：执行失败，错误信息：' . $e->getMessage());
        }
    }

}